package com.lezijie.seckill.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author 孙志鹏
 * @createDate 2021/10/26 20:45
 */
@Configuration
public class RedisConfig {

    /**
     * Redis序列化机制
     * @param redisConnectionFactory Redis连接工厂
     * @return 设置好的RedisTemplate对象
     */
    @Bean
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
        // 设置RedisKey的序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // 设置value的序列化功能, 选择使用GenericJackson2Json是对类的一个通用的序列化转换。
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        // hash类型，key序列化
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        // hash类型，vlaue的序列化
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        // 注入连接工厂
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        return redisTemplate;
    }
}
